/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frmRegistrarAsistenciaTallerCapacitacion.java
 *
 * Created on 10-may-2010, 17:22:27
 */

package vista.rrhh;

import com.itextpdf.text.DocumentException;
import controlador.rrhh.GestorRegistrarAsistenciaTallerCapacitacion;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

import util.NTupla;
import util.ReporteUtil;
import util.SwingPanel;
import util.TablaUtil;
import util.Tupla;
import vista.reportes.ReportDesigner;
import vista.reportes.sources.InformeAsistenciaTallerCapacitacion;

/**
 *
 * @author Administrador
 */
public class pantallaRegistrarAsistenciaTallerCapacitacion extends javax.swing.JInternalFrame {

    private GestorRegistrarAsistenciaTallerCapacitacion gestor;
    private int SELECTED_DetalleHorario = 0;


    /** Creates new form frmRegistrarAsistenciaTallerCapacitacion */
    public pantallaRegistrarAsistenciaTallerCapacitacion() {
        initComponents();
        
        this.gestor = new GestorRegistrarAsistenciaTallerCapacitacion(this);

        habilitarVentana();
        
    }

    private void habilitarVentana()
    {
        //initTablaAsistencia();
        mostrarTalleres();
    }

    private void initTablaAsistencia()
    {
        DefaultTableModel modelo = new DefaultTableModel();

        Object[] nombreColumnas = {"Nombre del Empleado","Asistencia"};
        for (int i = 0; i < nombreColumnas.length; i++)
        {
           modelo.addColumn(nombreColumnas[i]);
        }

        tblAsistencia.setModel(modelo);
    }

    private void mostrarTalleres()
    {
        ArrayList<Tupla> lista = gestor.buscarTalleresNoRealizados();

        DefaultComboBoxModel valores = new DefaultComboBoxModel();
        Iterator<Tupla> it = lista.iterator();

        if(lista.size()==0)
        {
            valores.addElement(new Tupla(0,"No hay Talleres de Capacitación Cargados"));
        }

        while(it.hasNext()){
            Tupla tu = it.next();
            valores.addElement(tu);
        }

        cmbTaller.setModel(valores);
    }

    private void cargarListaAsistencia()
    {
        if(cmbHora.getItemCount()!=0)
        {

            Tupla tx = (Tupla)cmbHora.getSelectedItem();

            if(tx.getId()!=0)
            {
                SELECTED_DetalleHorario = tx.getId();

                ArrayList<NTupla> lista = gestor.ListaAsistencia(tx.getId());

                DefaultTableModel modelo = (DefaultTableModel) tblAsistencia.getModel();
                modelo = TablaUtil.vaciarDefaultTableModel(modelo); // Limpio las filas

                Iterator it = lista.iterator();
                while (it.hasNext())
                {
                    NTupla nt = (NTupla) it.next();
                    Object[] fila = new Object[2];
                    fila[0] = nt;
                    fila[1] = nt.getData();
                    modelo.addRow(fila);
                }

                tblAsistencia.setModel(modelo);
            }
        }
        else
        {
            JOptionPane.showMessageDialog(this.getParent(),"Seleccione el horario de un Taller","Atención",JOptionPane.INFORMATION_MESSAGE);
        }
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        cmbFecha = new javax.swing.JComboBox();
        cmbHora = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        cmbTaller = new javax.swing.JComboBox();
        btnCargarLista = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblAsistencia = new javax.swing.JTable();
        btnCancelar = new javax.swing.JButton();
        btnGuardar = new javax.swing.JButton();
        btnImprimir = new javax.swing.JButton();
        btnMarcarTodos = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setTitle("Registrar Asistencia a un Taller de Capacitación");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del Taller"));

        jLabel1.setText("Fecha:");

        jLabel2.setText("Horario: ");

        cmbFecha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbFechaActionPerformed(evt);
            }
        });

        jLabel3.setText("Taller de Capacitación: ");

        cmbTaller.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbTallerActionPerformed(evt);
            }
        });

        btnCargarLista.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/iconos/var/16x16/download.png"))); // NOI18N
        btnCargarLista.setText("Cargar Lista");
        btnCargarLista.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCargarListaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnCargarLista, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmbTaller, 0, 319, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmbFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmbHora, 0, 157, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(cmbTaller, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(cmbHora, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(12, 12, 12)
                .addComponent(btnCargarLista))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Detalle de la Lista"));

        tblAsistencia.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Empleado", "Asistencia"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Boolean.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tblAsistencia);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 435, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 297, Short.MAX_VALUE)
                .addContainerGap())
        );

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/iconos/var/16x16/delete.png"))); // NOI18N
        btnCancelar.setText("Cerrar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/iconos/var/16x16/save_upload.png"))); // NOI18N
        btnGuardar.setText("Guardar Cambios");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/iconos/var/16x16/text_page.png"))); // NOI18N
        btnImprimir.setText("Imprimir");
        btnImprimir.setEnabled(false);
        btnImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImprimirActionPerformed(evt);
            }
        });

        btnMarcarTodos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/iconos/var/16x16/favorite.png"))); // NOI18N
        btnMarcarTodos.setText("Marcar Todos");
        btnMarcarTodos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMarcarTodosActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnMarcarTodos)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
                        .addComponent(btnImprimir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnGuardar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancelar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar)
                    .addComponent(btnGuardar)
                    .addComponent(btnImprimir)
                    .addComponent(btnMarcarTodos))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCargarListaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCargarListaActionPerformed

        cargarListaAsistencia();
        btnImprimir.setEnabled(true);
        
    }//GEN-LAST:event_btnCargarListaActionPerformed

    private void cmbTallerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbTallerActionPerformed

        Tupla tx = (Tupla)cmbTaller.getSelectedItem();
        if(tx.getId()!=0)
        {
            ArrayList<Tupla> lista = gestor.mostrarFechasDeTaller(tx);

            DefaultComboBoxModel valores = new DefaultComboBoxModel();
            Iterator<Tupla> it = lista.iterator();

            if(lista.isEmpty())
            {
                valores.addElement(new Tupla(0,"No hay Fechas para este taller"));
            }

            while(it.hasNext()){
                Tupla tu = it.next();
                valores.addElement(tu);
            }

            cmbFecha.setModel(valores);

        }


    }//GEN-LAST:event_cmbTallerActionPerformed

    private void cmbFechaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbFechaActionPerformed
        Tupla tx = (Tupla)cmbFecha.getSelectedItem();
        Tupla ty = (Tupla)cmbTaller.getSelectedItem();

        if(tx.getId()!=0)
        {
            ArrayList<Tupla> lista = gestor.mostrarHorariosDeTaller(ty,tx);

            DefaultComboBoxModel valores = new DefaultComboBoxModel();
            Iterator<Tupla> it = lista.iterator();

            if(lista.isEmpty())
            {
                valores.addElement(new Tupla(0,"No hay Horarios para este taller"));
            }

            while(it.hasNext()){
                Tupla tu = it.next();
                valores.addElement(tu);
            }

            cmbHora.setModel(valores);

        }
    }//GEN-LAST:event_cmbFechaActionPerformed

    private void marcarAsistenciaTodos()
    {
        DefaultTableModel modelo = (DefaultTableModel) tblAsistencia.getModel();
        int siz = modelo.getRowCount();
        for (int i = 0; i < siz; i++)
        {
            modelo.setValueAt(true,i,1);
        }
    }

    private void btnMarcarTodosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMarcarTodosActionPerformed

        marcarAsistenciaTodos();

    }//GEN-LAST:event_btnMarcarTodosActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed

        guardar();

    }//GEN-LAST:event_btnGuardarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed

        this.dispose();

    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImprimirActionPerformed
      if(SELECTED_DetalleHorario!=0)
      {
        // Bue, ahora viene la batatola, por suerte no valido
        // Recolecto los datos de la tabla
        ArrayList<NTupla> lista = new ArrayList<NTupla>();
        
        DefaultTableModel modelo = (DefaultTableModel) tblAsistencia.getModel();
        int siz = modelo.getRowCount();
        for (int i = 0; i < siz; i++)
        {
            NTupla nt;
            nt = (NTupla) modelo.getValueAt(i,0);
            nt.setData(modelo.getValueAt(i,1));
            lista.add(nt);
        }

        // Parametros
        HashMap<String,Object> params = new HashMap<String, Object>();
        Tupla tpTitulo = (Tupla) cmbTaller.getSelectedItem();
        params.put(InformeAsistenciaTallerCapacitacion.KEY_TITULO_CURSO,tpTitulo.getNombre());
        Tupla tpFecha = (Tupla) cmbFecha.getSelectedItem();
        params.put(InformeAsistenciaTallerCapacitacion.KEY_FECHA,tpFecha.getNombre());
        Tupla tpHorario = (Tupla) cmbHora.getSelectedItem();
        params.put(InformeAsistenciaTallerCapacitacion.KEY_HORARIO,tpHorario.getNombre());
        
        InformeAsistenciaTallerCapacitacion informe = new InformeAsistenciaTallerCapacitacion(lista);
        informe.setNombreReporte("Registro de Asistencia");
        informe.setNombreArchivo("AsistenciaTaller-"+tpTitulo.getNombre(),ReportDesigner.REPORTE_TIPO_OTROS);
        
        try {
            informe.makeAndShow(params);
        } catch (DocumentException ex) {
            mostrarMensaje(JOptionPane.ERROR_MESSAGE,"Error!","No se pudo crear el informe\nVerifique los datos e intentelo nuevamente");
        } catch (FileNotFoundException ex) {
            mostrarMensaje(JOptionPane.ERROR_MESSAGE,"Error!","No se pudo crear el archivo donde guardar el informe");
        }
        
      }
    }//GEN-LAST:event_btnImprimirActionPerformed

    /**
     * Muestra un mensaje
     * @param tipo
     * @param titulo
     * @param mensaje 
     */
    public void mostrarMensaje(int tipo,String titulo,String mensaje)
    {
         JOptionPane.showMessageDialog(this.getParent(),mensaje,titulo,tipo);
    } 
        

    /**
     * EL-0002 : No se pudo cargar el combo de talleres de capacitacion
     * EL-0003 : No se pudo cargar la lista de Fechas del Taller
     * EL-0004 : No se pudo cargar la lista de Horarios del Taller
     * EL-0005 : No se pudo cargar la lista de Asistencia
     * EG-0006 : No se pudo guardar la lista de asistencia
     * MI-0002 : Se registraron los cambios en la lista de Asistencia
     * @param cod
     */
    public void MostrarMensaje(String cod)
    {
        System.out.println("Se detecto el mensaje: "+cod);
        if(cod.equals("EL-0002"))
        {
            JOptionPane.showMessageDialog(this.getParent(),"No se pudo cargar la lista de Talleres de Capacitación","Error en la Carga",JOptionPane.ERROR_MESSAGE);
        }
        if(cod.equals("EL-0003"))
        {
            JOptionPane.showMessageDialog(this.getParent(),"No se pudo cargar la lista de Fechas del Taller","Error en la Carga",JOptionPane.ERROR_MESSAGE);
        }
        if(cod.equals("EL-0004"))
        {
            JOptionPane.showMessageDialog(this.getParent(),"No se pudo cargar la lista de Horarios del Taller","Error en la Carga",JOptionPane.ERROR_MESSAGE);
        }
        if(cod.equals("EL-0005"))
        {
            JOptionPane.showMessageDialog(this.getParent(),"No se pudo cargar la lista de Asistencia","Error en la Carga",JOptionPane.ERROR_MESSAGE);
        }
        if(cod.equals("EL-0006"))
        {
            JOptionPane.showMessageDialog(this.getParent(),"No se pudo Guardar la lista de asistencia","Error en la Registración",JOptionPane.ERROR_MESSAGE);
        }
        if(cod.equals("MI-0002"))
        {
            JOptionPane.showMessageDialog(this.getParent(),"Se registraron los cambios en la lista de Asistencia","Registración Exitosa",JOptionPane.INFORMATION_MESSAGE);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnCargarLista;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnImprimir;
    private javax.swing.JButton btnMarcarTodos;
    private javax.swing.JComboBox cmbFecha;
    private javax.swing.JComboBox cmbHora;
    private javax.swing.JComboBox cmbTaller;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblAsistencia;
    // End of variables declaration//GEN-END:variables

    private void guardar() {
        // Bue, ahora viene la batatola, por suerte no valido
        // Recolecto los datos de la tabla
        ArrayList<NTupla> lista = new ArrayList<NTupla>();
        
        DefaultTableModel modelo = (DefaultTableModel) tblAsistencia.getModel();
        int siz = modelo.getRowCount();
        for (int i = 0; i < siz; i++)
        {
            NTupla nt;
            nt = (NTupla) modelo.getValueAt(i,0);
            nt.setData(modelo.getValueAt(i,1));
            lista.add(nt);
        }

        gestor.confirmarListaAsistencia(lista);
    }


}
